package com.lfm.friend.controller;

import com.lfm.core.constants.HttpConstants;
import com.lfm.core.controller.BaseController;
import com.lfm.core.domain.R;
import com.lfm.core.enums.ResultCode;
import com.lfm.friend.domain.dto.UserDTO;
import com.lfm.friend.service.IUserService;
import com.lfm.security.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    //  /user/login
    @PostMapping("/login")
    public R<String> login(@RequestBody UserDTO userDTO) {
        if(!checkPhone(userDTO.getPhone())){
            throw new ServiceException(ResultCode.FAILED_USER_PHONE);
        }
        return R.ok(userService.login(userDTO.getPhone(), userDTO.getPassword()));
    }

    //  /user/logout
    @DeleteMapping("/logout")
    public R<Void> logout(@RequestHeader(HttpConstants.AUTHENTICATION) String token) {
        return toR(userService.logout(token));
    }

    public static boolean checkPhone(String phone) {
        Pattern regex = Pattern.compile("^1[2|3|4|5|6|7|8|9][0-9]\\d{8}$");
        Matcher matcher = regex.matcher(phone);
        return matcher.matches();
    }
}
